<?php
/**
 * Created by PhpStorm.
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 7/9/16
 * Time: 00:19
 */

namespace Home\Model;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Home\Model\PositionModel;

use Think\Log;
use Think\Model;

class FinishModel {
    const CURRENT_MONTH_REPAY = 0;
    const NEXT_MONTH_REPAY = 1;
    const TWO_MONTH_LATER_REPAY = 2;

    const SYSTEM_STANDARD   = 1;
    const SYSTEM_DISCOUNT   = 2;
    const PROVINCE_STANDARD = 3;
    const PROVINCE_DISCOUNT = 4;
    const MERCHANT_STANDARD = 5;
    const MERCHANT_DISCOUNT = 6;

    /*** 现金贷下单数据入库 ***/
    public function WithdrawalOrderFinish($consume_id)
    {
        //获取当前订单的状态
        $cur_order = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
        
        if(!$cur_order){
            BusinessException::throwException(Constant::ORDER_ID_NOT_FOUNT);
        }
        if(($cur_order['type'] != Constant::PAY_TYPE_WITHDRAWAL)
            || ($cur_order['status'] != ConsumeHistoryModel::STATUS_WAITING_REPAY)){
            BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
        }

        //校验用户是否存在
        $customer = M('Customer')->where(['id'=>$cur_order['customer_id']])->find();
        Log::write("订单信息：".json_encode($cur_order, JSON_UNESCAPED_UNICODE), Log::INFO);

        //用户余额是否足够
        if($cur_order['amount'] > $customer['balance_cash_amount']) {
            BusinessException::throwException(Constant::NO_ENOUGH_BALANCE);
        }
        
        //用户订单数据，录入分期数据及账单数据
        $conf = M('SysInstallmentPlan')->where(['id'=>$cur_order['repay_id']])->find();
        $config['repay_times'] = $conf['repay_times'];
        $config['interest_rate'] = $conf['interest_rate'];
        $config['cut_interest'] = $conf['cut_interest'];
        $config['repay_unit'] = $conf['repay_unit'];
        $config['timer'] = $conf['timer'];
        $res = $this->insCustomerBill($cur_order, [], $config);
        
        Log::write("用户订单数据录入：".json_encode($res, JSON_UNESCAPED_UNICODE), Log::INFO);

        //获取银行卡信息(目前只有一张银行卡)
        $card_num = $bank_name = '';
        //$card_list = D('CustomerBankInfo')->getList($cur_order['customer_id']);
        /******************************获取默认银行卡|***************************************/
        $card_list = D('CustomerBankInfo')->getList($cur_order['customer_id']);
        $card_default_list = D('CustomerBankInfo')->getDefaultList($cur_order['customer_id']);
        Log::borrow_write("*****************用户提现|数据库获取默认银行卡：*****：".json_encode($card_default_list));

        /******************************获取默认银行卡|***************************************/
        if($card_default_list){
            $card_list= $card_default_list;
        }
        if($card_list){
            $card_num = $card_list[0]['card_num'];
            $bank_name = $card_list[0]['bank_name'];
        }
        /******************************获取默认银行卡|***************************************/
        //if($card_default_list){
          //  $card_num = $card_default_list['card_num'];
            //$bank_name = $card_default_list['bank_name'];
        //}
        //Log::borrow_write("*****************用户提现|数据库获取默认银行卡：*****：".json_encode($card_default_list));

        /******************************获取默认银行卡|***************************************/
        //提现（德哥接口）
        $model = 'Pay/CustomerWithdraw';
        $xml_data = [
            'customer_id' => $cur_order['customer_id'],
            'consume_id' => $consume_id,
            'money' => $res['withdrawal_amount']
        ];
        
        Log::write('Pay/CustomerWithdraw:'.json_encode($xml_data), Log::DEBUG);
        Log::borrow_write("*****************用户".$cur_order['customer_id']."提现执行操作：入参：*****：".json_encode($xml_data));
        $ajax_ret = D('Ajax')->ajaxPost($model, $xml_data);
        Log::borrow_write("*****************用户".$cur_order['customer_id']."提现执行操作：返回结果：*****：".$ajax_ret."|返回信息：".$ajax_ret['msg']);
       $ret = json_decode(trim($ajax_ret,chr(239).chr(187).chr(191)),true);
        if($ret['code'] == 0){
            Log::borrow_write("*****************CustomerWithdraw用户放款|付款成功|*****：");

            $success['repayment_time'] = (isset($config['timer'])&&$config['timer']>0) ? add_days($config['timer']-1) : get_repayment_date(1);
            $success['status'] = ConsumeHistoryModel::STATUS_REVIEWED;
            //资金
            $financing = D("Customer")->where(['id' => $cur_order['customer_id']])->find();
            $params = C();
            //身份证号在配置白名单，略过资金端引擎
            //if(!in_array($financing['id_num'],$params[WHITE_LIST])) {
                $financing['need_money'] = $cur_order['amount']; //单位分
                $financing['consume_id'] = $consume_id;
                 Log::borrow_write("*****************用户提现成功|资金引擎|：*****：");
                $ret = BaseHook::executePayWayHook("PAYWAY_ENGINE_HOOK", $financing);
                Log::borrow_write("*****************用户提现成功|资金引擎|执行结果：".json_encode($ret)."*****：");
                if($ret['code'] == 0 || $ret['data']){
                    $success['payway'] = $ret['data']['payway'];
                }
            //}
            if(false === M('ConsumeHistory')->where(['id' => $cur_order['id']])->save($success)){
                Log::write("借款引擎失败：sql=".M()->getLastSql(), Log::ERR);
                Log::borrow_write("*****************CustomerWithdraw用户放款|借款引擎失败|*****：");
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            Log::borrow_write("*****************提现成功！customer_id|：".$cur_order['customer_id']."*****：");
            Log::write("提现成功！customer_id=".$cur_order['customer_id'], Log::DEBUG);
        }else{
            Log::write("*********用户".$cur_order['customer_id']."提现失败！errmsg=".json_decode($ret['msg'], JSON_UNESCAPED_UNICODE), Log::DEBUG);
            Log::borrow_write("*********用户".$cur_order['customer_id']."提现失败！errmsg=".json_decode($ret['msg'], JSON_UNESCAPED_UNICODE));

            BusinessException::throwException($ret['msg']);
        }

        $res2App = [
            'amount' => $cur_order['consume_amount'],
            'transfer_amount' => $res['withdrawal_amount'],
            'consume_time' => date('Y-m-d H:i:s', $cur_order['add_time']),
            'transfer_time' => '24小时之内到账',
            'card_num' => $card_num,
            'bank_name' => $bank_name,
            'repay_times' => $config['repay_times'],
            'timer' => $config['timer'],
            'repay_amount' => $res['repay_total'],
            'repay_unit' => $config['repay_unit']
        ];

        return $res2App;
    }

    /*** 分期下单数据入库 ***/
    public function OrderFinish($consume_id)
    {
        //获取当前订单的状态
        $cur_order = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
        if(!$cur_order){
            BusinessException::throwException(Constant::ORDER_ID_NOT_FOUNT);
        }
        if(($cur_order['type'] == Constant::PAY_TYPE_INSTALLMENT || $cur_order['type'] == Constant::PAY_TYPE_NEXT_MONTH)
            && $cur_order['status'] != ConsumeHistoryModel::STATUS_WAITING_REPAY){
            BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
        }

        //校验用户、商户是否存在
        D('Customer')->has(['id'=>$cur_order['customer_id']]);
        D('Merchant')->has(['id'=>$cur_order['merchant_id']]);
        Log::write("订单信息：".json_encode($cur_order, JSON_UNESCAPED_UNICODE), Log::INFO);

        //订单首付金额是否已付款
        if($cur_order['down_payment'] > 0){
            $cur_down = M('CustomerBillPayLog')->where(['customer_id'=>$cur_order['customer_id'], 'consume_id'=>$consume_id,
                'type' => Constant::PAYMENT_TYPE_DOWN_PAYMENT, 'publish'=>1, 'trade_state'=>'TRADE_SUCCESS'])->find();
            if(!$cur_down){
                BusinessException::throwException(Constant::DOWN_PAYMENT_NO_PAY);
            }else if($cur_down['amount'] < $cur_order['down_payment']){
                BusinessException::throwException(Constant::DOWN_PAYMENT_NOT_ENOUGH);
            }
        }

        //获取当前用户信审金额
        $vetting = M('CreditVetting')->where(['consume_id'=>$consume_id, 'status'=>['in', CreditVettingModel::STATUS_MANUAL_REVIEWED.", ".CreditVettingModel::STATUS_AUTO_REVIEWED]])->find();
        if(!$vetting){
            Log::write("获取信审额度出错：sql=".M('CreditVetting')->getLastSql(), Log::ERR);
            BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
        }

        //资金
        $financing = D("Customer")->where(['id' => $cur_order['customer_id']])->find();
        $params = C();
        //身份证号在配置白名单，略过资金端引擎
        if(!in_array($financing['id_num'],$params[WHITE_LIST])) {
            $financing['need_money'] = $cur_order['amount']; //单位分
            $financing['consume_id'] = $consume_id;
            $ret = BaseHook::executePayWayHook("PAYWAY_ENGINE_HOOK", $financing);
            if($ret['code'] == 0 || $ret['data']){
                if(false === M('ConsumeHistory')->where(['id' => $cur_order['id']])->setField('payway', $ret['data']['payway'])){
                    Log::write("借款引擎失败：sql=".M()->getLastSql(), Log::ERR);
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }
        }

        //开启事务
        M('Finish')->startTrans();

        //查询用户预订单金额计算
        $customer = D('Customer')->has(['id'=>$cur_order['customer_id']]);
        if($cur_order['type'] == Constant::PAY_TYPE_ZERO_APPLY){
            $sql = "UPDATE customer SET balance_amount = balance_amount + ".$vetting['credit_amount'].",
                    amount = amount + ".$vetting['credit_amount']." WHERE id = ".$cur_order['customer_id'];
            Log::write("更新用户授信额度sql=".$sql, Log::INFO);
            $upd = M('Customer')->execute($sql);
            Log::write("更新用户授信额度结果：return=".$upd, Log::INFO);
            if(false === $upd){
                Log::write("更新用户授信额度失败：return=".$upd.",sql=".$sql, Log::ERR);
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            //数据全部执行完毕，更新消费记录状态为系统已判断好的状态
            if(false === M('ConsumeHistory')->where(['id' => $cur_order['id']])->setField('status', ConsumeHistoryModel::STATUS_REVIEWED)){
                Log::write("更新用户消费记录失败：return=".$upd.",sql=".$sql, Log::ERR);
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
        }else{
            $merchant = D('Merchant')->has(['id'=>$cur_order['merchant_id']]);
            $arrAmount['amount'] = $cur_order['consume_amount'];
            $arrAmount['down_type'] = $cur_order['down_type'];
            $arrAmount['down_payment'] = $cur_order['down_payment'];
            $money = $this->preFacilityForCommon($customer,$merchant, $arrAmount);
            Log::write("预订单金额：".json_encode($money, JSON_UNESCAPED_UNICODE), Log::INFO);

            //用户订单数据，录入分期数据及账单数据
            $config = $this->getInterestStandardConf($cur_order['merchant_id'], $cur_order['repay_id']);
            if($cur_order['discount_interest'] == FinishModel::SYSTEM_DISCOUNT && $config['discount_interest']){
                $config['interest_rate'] = $config['discount_interest'];
                $config['interest_type'] = FinishModel::SYSTEM_DISCOUNT;
            }
            $res = $this->insCustomerBill($cur_order, $vetting, $config);
            Log::write("用户订单数据录入：".json_encode($res, JSON_UNESCAPED_UNICODE), Log::INFO);

            //给商户打钱
            D("MerchantUser")->updateBalance($cur_order['merchant_id'], $money['merchant_gain_amount']);

            //返利佣金入库(次月转分期不计佣金)
            $arr = M("Merchant")->field('is_commission,is_keyman,rebate_type')->where(['id'=> $cur_order['merchant_id']])->find();
            if($arr['is_commission']){//是否支持佣金
                $is_keyman = $arr['is_keyman'];
                $rebate_type = $arr['rebate_type'];
            }
            $other = M('ConsumeHistory')->where(['id' => $cur_order['id']])->select();
            $other =  $other[0];
            if($other['type']==2 && $other['status'] ==1 && $other['discount_interest'] != 2){//订单完成
                if($arr['is_commission'] ==1 && $rebate_type == 1) {//支持佣金//0-延迟返利 订单完成时不返利 //1-立即返利
                    $sales_volume = $other['amount'];//销售额
                   
                    $yongjin = M("Merchant")->field('rebate_overdue,rebate_type')->where(['id'=> $cur_order['merchant_id']])->find();
                    $commission['rebate_rate'] = $yongjin['rebate_overdue'];
                    $point_first = $commission['rebate_rate'];//返点
                    $money = ceil($sales_volume * $point_first);
                    $merchantId = $cur_order['merchant_id'];
                    Log::write("返佣111：".$money,Log::DEBUG);
                    //查询佣金余额
                    $arr_commission = M('MerchantUser')->field('commision_balance')->where(['merchant_id' => $merchantId])->find();
                    if ($arr_commission['commision_balance'] < 0) {
                        $money1 = ceil($money + $arr_commission['commision_balance']);
                    }
                    //更新返利佣金金额
                    M('MerchantUser')->execute("UPDATE `merchant_user` SET `commision_balance`= commision_balance + $money  WHERE  `merchant_id` = '$merchantId'");
                    Log::write("佣金余额".$arr_commission['commision_balance']."本次佣金".$money1,Log::DEBUG);
                    if ($money + $arr_commission['commision_balance'] > 0) {
                        //商户 销售额余额  佣金余额
                        $merchant_info = M('MerchantUser')->field('commision_balance,balance')->where(['merchant_id' => $merchantId])->find();
                        if($arr_commission['commision_balance']<0) {//原佣金余额为负
                            $new_balance = $merchant_info['balance'] + $money1;
                            $new_commision_balance = $merchant_info['commision_balance'] - $money1;
                        }else{
                            $new_balance = $merchant_info['balance'] + $money;
                            $new_commision_balance = $merchant_info['commision_balance'] - $money;
                        }
                        Log::write("佣金余额".$arr_commission['commision_balance']."本次佣金".$money,Log::DEBUG);
                        M('MerchantUser')->where(['merchant_id' => $merchantId])->setField(['balance' => $new_balance, 'commision_balance' => $new_commision_balance]);
                        //提现日志入库
                        $MerchantPayLog = M('MerchantCommissionLog');
                        $order_id = A("Pay")->trade_no();
                        $mer_date = date('Ymd');
                        $create_time = date("Y-m-d H:i:s",time());
                        //入库
                        if($arr_commission['commision_balance']<0) {//原佣金余额为负
                            $getmoney =  $money + $arr_commission['commision_balance'];
                        }else{
                            $getmoney =  $money;
                        }
                        $data = array(
                            'order_id' => $order_id,
                            'merchant_id' => $merchantId,
                            'money' => $getmoney,
                            'balance_old' => $merchant_info['balance'],
                            'transfer_date' => $mer_date,
                             'create_time' =>$create_time,
                        );
                        Log::write('MerchantCommissionLog' . json_encode($data), Log::DEBUG);
                        $MerchantPayLog->add($data);
                    }
                }
            }


        }

        //发送短信

        //获取用户最新的信用额度值
        /*$newCustomer = M('customer')->where(['id' => $cur_order['customer_id']])->field('amount, balance_amount')->find();
        $res2App = [
            'amount' => $cur_order['consume_amount'],
            'repay_type' => $cur_order['type'],
            'repay_date' => Constant::BILL_LAST_DAY,
            'repay_total' => $cur_order['amount'],
            'credit' => $newCustomer['amount'],
            'balance_amount' => $newCustomer['balance_amount'],
            'max_amount' => Constant::MAX_CREDIT_AMOUNT,
            'discount' => $money['discount_first_order'] + $money['discount_full_reduce'] + $money['discount_rebate_amount'],
            'real_pay' => $money['amount'],
            'down_payment' => $cur_order['down_payment']
        ];

        if($cur_order['type'] == Constant::PAY_TYPE_INSTALLMENT){
            //计算分期本金和利息,单位分
            $res2App['repay_times'] = Constant::REPAY_TIMES;
            $res2App['repay_principal'] = $res['repay_principal'];
            $res2App['repay_interest'] = $res['repay_interest'];
            $res2App['repay_total'] = $res['repay_total'];
        }*/

        return true;
    }

    /*************************************************************************
     * 功能描述：记录消费历史详情信息
     * 创建时间：2016-8-14
     *************************************************************************/
    public function insCustomerBill($cur_order, $vetting, $config=NULL)
    {
        Log::write("[".ACTION_NAME."][insCustomerBill][customer_id=".$cur_order['customer_id']."]:start", Log::INFO);
        $customerId = $cur_order['customer_id'];

        //分期还款方式，记录分期还款明细
        if(Constant::PAY_TYPE_INSTALLMENT == $cur_order['type'] || Constant::PAY_TYPE_WITHDRAWAL == $cur_order['type']){
            Log::write("[".ACTION_NAME."][insCustomerBill][config=".json_encode($config)."]:start", Log::INFO);
            if(!($installment = $this->insConsumeInstallmentDetail($cur_order['amount'],$cur_order['id'], $config))){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
        }

        //账单数据录入
        if(!($billId = D('CustomerBill')->insCustomerBillDetail($cur_order, $config))){
            BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
        }

        if(Constant::PAY_TYPE_WITHDRAWAL != $cur_order['type']){
            if($vetting['credit_amount'] || $cur_order['amount']){
                $sql = "UPDATE customer SET balance_amount = balance_amount + ".$vetting['credit_amount']." - ".$cur_order['amount'].",
             amount = amount + ".$vetting['credit_amount']." WHERE id = ".$customerId;
                
                $upd = M('Customer')->execute($sql);
                Log::write("更新用户授信额度失败：return=".$upd.",sql=".$sql, Log::INFO);
                if(false === $upd){
                    Log::write("更新用户授信额度失败：return=".$upd.",sql=".$sql, Log::ERR);
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
            }
            //数据全部执行完毕，更新消费记录状态为系统已判断好的状态
            $upd_data['status'] = ConsumeHistoryModel::STATUS_REVIEWED;
            $upd_data['add_time'] = time();
            if(isset($config['interest_type'])){
                $upd_data['discount_interest'] = $config['interest_type'];
            }
            if(false === M('ConsumeHistory')->where(['id' => $cur_order['id']])->setField($upd_data)){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
        }else{
            //数据全部执行完毕，更新消费记录状态为系统已判断好的状态
            if(false === M('ConsumeHistory')->where(['id' => $cur_order['id']])->setField(['amount'=>$installment['withdrawal_amount']])){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
        }

        //审核通过且为首次激活，则需要给用户授权信用额度
        /*if($vetting['status'] ){
            if(false === M('CreditVetting')->where(['consume_id' => $cur_order['id']])->setField('status', ConsumeHistoryModel::STATUS_REVIEWED)){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
        }*/

        Log::write("[insCustomerBill]:return=>".json_encode($installment, JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][insCustomerBill]:end\n", Log::INFO);

        return $installment;
    }

    /*************************************************************************
     * 功能描述：授信额度、优惠金额计算
     * 创建时间：2016-8-13
     *************************************************************************/
    public function preFacilityForCommon($customer, $merchant, $arrAmount)
    {
        Log::write("[".ACTION_NAME."][preFacilityForCommon][customer_id=".$customer['id']."]:start", Log::INFO);
        //校验用户是否已经参加过优惠活动
        $act = M('CustomerActivity')->where(['recommend_mobile'=>$customer['mobile']])->count('id');

        //实付金额 = 当前实付金额 - 首单优惠金额
        $discountFirstOrder = 0;
        $consume_amount = $arrAmount['amount'];
        $amount = $arrAmount['amount'];
        if (0 == $act && 0 == $customer['order_count'] && $merchant['discount_first_order'] > 0) {
            /* 用户消费金额   活动优惠金额  实际优惠金额
             *     100             5             5
             *      3              5             3
             */
            $discountFirstOrder = ($amount-$merchant['discount_first_order'])>0 ? $merchant['discount_first_order'] : $amount; //首先优惠金额
            $amount -= $discountFirstOrder;
        }

        /* 特殊案例剖析：优先优惠平台金额，消费金额小于优惠金额时最大优惠金额为用户消费金额，不会倒贴
         * 商家优惠类型  平台优惠   用户消费金额   平台实际优惠金额  商家实际优惠金额  实际优惠金额
         *  满5元减2元        5          5              5              0                   5
         *  满5元减2元        5          3              3              0                   3
         *  满10元减2元       5         10              5              2                   7
         *   打6折            5          5              3              0                   5
         *   打6折           5          3              3              0                   3
         *   打6折           5         10              5              3                   8         */

        // 商户满减优惠：实付金额 = 当前实付金额 - 满减优惠
        $discountFullReduce = 0;
        if ($merchant['discount_full_amount'] && $merchant['discount_full_reduce']) {
            // 原始的消费金额 > 满减金额 ===> 满足优惠条件
            if ($consume_amount >= $merchant['discount_full_amount']) {
                $discountFullReduce = ($amount-$merchant['discount_full_reduce']>0) ? $merchant['discount_full_reduce'] : $amount;
                //实付金额 = 当前实付金额 - 满减优惠
                $amount -= $discountFullReduce;
            }
        }
        // 商户折扣优惠
        $discountRebate = 0;
        if ($merchant['discount_rebate']) {
            // 计算商户折扣金额(扣减商家金额按四舍五入的方式)
            $discountRebatePre = round(($consume_amount * (100-$merchant['discount_rebate']*10))/100.0);
            $discountRebate = ($amount-$discountRebatePre>0) ? $discountRebatePre : $amount;
            $amount -= $discountRebate;
        }

        // 什么情况下系统都不会倒贴钱，这个条件不会发生，暂时保留
        if ($amount < 0) {
            $amount = 0;
        }

        // 正常情况：商户应得的金额 = $consumeAmount(用户消费原金额) - $discountFullReduce(商户满减优惠)-$discountRebate（商家折扣优惠）+（平台优惠金额）
        // 如果所有优惠金额大于用户消费金额，上面的算法就会出现负值，因此采用如下计算方法：
        // 商户应得的金额 = 用户实付金额(>=0) + 平台优惠金额
        $merchantGainAmount = $amount + $discountFirstOrder;

        //计算首付金额，取整到元
        $downPayment = 0;
        if($amount > Constant::DOWN_PAYMENT_START){
            if($arrAmount['down_type'] == Constant::DOWN_AUTO){
                if($amount - Constant::DOWN_PAYMENT_LIMIT < $amount*Constant::DOWN_PAYMENT_DISCOUNT){
                    $downPayment = floor(($amount*Constant::DOWN_PAYMENT_DISCOUNT)/100)*100;
                }else{
                    $downPayment = $amount - Constant::DOWN_PAYMENT_LIMIT;
                }
            }else if($arrAmount['down_type'] == Constant::DOWN_CUSTOM){
                $downPayment = $arrAmount['down_payment'] ? $arrAmount['down_payment'] : 0;
            }

            if($amount < $downPayment){
                BusinessException::throwException(Constant::AMOUNT_LG_DOWN);
            }
            //借款金额
            $amount = $amount - $downPayment;
        }

        $data = [
            'discount_first_order'   => $discountFirstOrder,
            'discount_full_reduce'   => $discountFullReduce,
            'discount_rebate_amount' => $discountRebate,
            'merchant_gain_amount'   => $merchantGainAmount,
            'amount'                   => $amount,
            'consume_amount'          => $consume_amount,
            'down_payment'            => $downPayment,
            'discount_amount'         => $discountFirstOrder + $discountFullReduce + $discountRebate
        ];
        Log::write("[preFacilityForCommon]:return=>".json_encode($data,JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][preFacilityForCommon]:end\n", Log::INFO);

        return $data;
    }

    /*************************************************************************
     * 功能描述：记录消费历史详情信息
     * 创建时间：2016-8-14
     *************************************************************************/
    public function insConsumeInstallmentDetail($amount, $insertId, $config=NULL, $repay_diff_cur_month=1)
    {
        Log::write("[".ACTION_NAME."][insConsumeInstallmentDetail]:start", Log::INFO);

        //利息计算
        $new_conf = $config;
        $new_conf['repay_times'] = $config['timer'];
        $installmentDetail = $this->getWithdrawalDetail($amount, $new_conf, $new_conf['repay_unit']);
        $currentRepayment = $installmentDetail['bill'];
        $withdrawal_amount = $installmentDetail['withdrawal_amount'];

        //生成分期明细
        $installmentData = [];
        // $repay_diff_cur_month：0-本月开始还款  1-下月开始还款  2-下下个月后开始还款...
        $repayTimes = isset($config['repay_times'])? $config['repay_times'] : Constant::REPAY_WITHD_TIMES;

        //判断是否逾期（转分期）
        $v = M('ConsumeHistory')->where(['id'=>$insertId])->field('repayment_time,DATEDIFF(FROM_UNIXTIME(repayment_time, "%Y-%m-%d"),CURDATE()) AS fine_date')->find();
        if ($v['fine_date'][0] == '-') {
            if (intval(substr($v['fine_date'], 1)) > 3) {
                $fine = $v['amount'] * Constant::WITHDRAWAL_FINE * intval(substr($v['fine_date'], 1));
            }
            $repay_diff_cur_month = 0;
            Log::write("repay_diff_cur_month1=".$repay_diff_cur_month.",fine=".$v['fine_date'][0], Log::DEBUG);
        }else {//未逾期
            $fine = 0;
            //判断还款日期是否在本月 
            if(date('m') != date('m',$v['repayment_time'])){
                $repay_diff_cur_month = 1;
            }
            Log::write("repay_diff_cur_month2=".$repay_diff_cur_month.",fine=".date('m') != date('m',$v['repayment_time']), Log::DEBUG);
        }

        for ($i = $repay_diff_cur_month; $i < $repayTimes+$repay_diff_cur_month; $i++) {
            $repaymentTime = isset($config['timer'])&&$config['timer']>0 ? add_days($config['timer']*$i-1) : get_repayment_date($i);
            if($i == $repay_diff_cur_month){
                $currentRepayment = $currentRepayment + $fine;
            }
            $installmentData[] = [
                'amount' => $currentRepayment,
                'parent_id' => $insertId,
                'repayment_time' => $repaymentTime,
                'add_time' => time()
            ];
            Log::write("conf=".json_encode($config).",installment=".json_encode($installmentData), Log::DEBUG);
            Log::write("i=".$i."repayment_time=".add_days($config['timer']*$i).",111=".get_repayment_date($i), Log::DEBUG);
        }
        if (!($installmentId = D('ConsumeInstallmentHistory')->addAll($installmentData))) {
            BusinessException::throwException(Constant::FAILED);
        }
        $data = [
            'repay_times'      => $repayTimes,
            'repay_principal'  => $installmentDetail['principal'],
            'repay_interest'   => $installmentDetail['interest'],
            'repay_total'      => $currentRepayment,
            'withdrawal_amount' => $withdrawal_amount
        ];
        Log::write("[insConsumeInstallmentDetail]:return=>".json_encode($data, JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][insConsumeInstallmentDetail]:end\n", Log::INFO);

        return $data;
    }

    /**
     * 计算分期本金和利息,单位分
     * @param int $amount
     * @return array
     */
    public function getInstallmentDetail($amount, $config=NULL)
    {
        $repayTimes = isset($config['repay_times'])? $config['repay_times'] : Constant::REPAY_TIMES;
        $rate  = isset($config['interest_rate'])? $config['interest_rate'] : Constant::INTEREST_RATE;
        return D("CustomerBill")->getInstallmentDetail($amount, $repayTimes, $rate);
    }

    /**
     * 计算现金贷每月应还,单位分
     * @param int $amount
     * @return array
     */
    public function getWithdrawalDetail($amount, $config=NULL, $repay_unit=1)
    {
        
        $res = [];
        if($repay_unit == 1){
            $repay_times = isset($config['repay_times'])? $config['repay_times'] : Constant::REPAY_TIMES;
            $rate = isset($config['interest_rate'])? $config['interest_rate'] : Constant::INTEREST_RATE;
            $cut_interest = isset($config['cut_interest'])? $config['cut_interest'] : 0;
            $cut_interest = $amount * $cut_interest;
            $principal = ceil($amount / $repay_times);
            $interest = ceil($amount * $rate);
            $res['withdrawal_amount'] = ceil(($amount - $cut_interest)/100)*100;
            $res['bill'] = ceil(($amount + $amount*$rate*$repay_times - $cut_interest)/$repay_times/100)*100;
            $res['principal'] = $principal;
            $res['interest'] = $interest;
            $res['timer']= $config["timer"];
        }else if($repay_unit == 2){
            $repay_times = isset($config['repay_times'])? $config['repay_times'] : Constant::REPAY_TIMES;
            $rate = isset($config['interest_rate'])? $config['interest_rate'] : Constant::INTEREST_RATE;
            $timer = $config['timer'];
            $cut_interest = isset($config['cut_interest'])? $config['cut_interest'] : 0;
            $cut_interest = $amount * $cut_interest;
            $principal = ceil($amount / $repay_times);
            $interest = ceil($amount * $rate * $timer);
            $res['withdrawal_amount'] = ceil(($amount - $cut_interest)/100)*100;
            $res['feeAmount'] = ceil(($cut_interest)/100)*100;
            //$res['bill'] = ceil(($amount + $amount*$rate*$timer - $cut_interest)/100)*100;
            $res['bill'] = ceil(($amount)/100)*100;
            $res['principal'] = $principal;
            $res['interest'] = $interest;
            $res['timer']= $config["timer"];
        }

        
        return $res;
    }

    /**
     * 批量计算分期本金和利息,单位分
     * @param int $amount
     * @return array
     */
    public function getAllInstallmentDetail($amount, $merchant_id, $target = 1, $changeToInstll = false)
    {
        //获取标配产品
        $res = M('SysInstallmentPlan')->order('repay_times')->where(['publish'=>1, 'target'=>$target, 'county_id'=>0])->select();
        $ret = [];
        if(is_array($res)){
            $i = 0;
            foreach ($res as $k=>$v){
                //如果$nextMonth次月为false，则表示不展示次月分期信息
                if($changeToInstll && $v['repay_times'] == 1){
                    continue;
                }
                //获取该产品的真正使用的利率
                $result = $this->getInterestStandardConf($merchant_id, $v['id']);

                //计算分期利息信息
                $gets = D("CustomerBill")->getInstallmentDetail($amount, $result['repay_times'], $result['interest_rate']);
                $ret[$i]['id'] = $result['id'];
                $ret[$i]['repay_times'] = $result['repay_times'];
                $ret[$i]['repay_total'] = $gets['bill'];
                if($changeToInstll){
                    $ret[$i]['pay_principal'] = $gets['principal'];
                    $ret[$i]['pay_interest'] = $gets['interest'];
                   // $ret[$i]['repay_date'] = Constant::BILL_LAST_DAY;//每月10号还款
                    //$ret[$i]['repay_date'] = get_repayment_date(1);
                }
                $i++;
            }
        }

        return $ret;
    }

    //获取利息标配信率信息
    public function getInterestStandardConf($merchant_id, $repay_id)
    {
        /* 标配利率优先级：默认标配利率 < 区域标配利率 < 商户标配利率 */
        $conf = M('SysInstallmentPlan')->where(['id'=>$repay_id])->find();
        $config['id'] = $repay_id;
        $config['repay_times'] = $conf['repay_times'];
        $config['discount_interest'] = $conf['discount_interest'];
        $config['interest_rate'] = $conf['interest_rate'];
        $config['interest_type'] = FinishModel::SYSTEM_STANDARD;

        //获取商户区域id
        $county_id = M('Merchant')->where(['id'=>$merchant_id])->field('county_id')->find();
        if(!$county_id){
            BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
        }
        $province_id = D('Position')->getProvinceIDByCountyID($county_id['county_id']);

        //利率选择
        //如果商户有优惠利息，则按商户优惠利息计算
        $merchant = M('MerchantInstallmentPlan')->where(['merchant_id'=>$merchant_id, 'repay_times'=>$conf['repay_times'], 'publish'=>1])->find();
        Log::write("商户优惠利息:".json_encode($merchant).",".$merchant['interest_rate'],Log::DEBUG);
        if($merchant && $merchant['interest_rate']>0){
            $config['interest_rate'] = $merchant['interest_rate'];
            $config['interest_type'] = FinishModel::MERCHANT_STANDARD;
            if($merchant['discount_interest']>0){
                $config['discount_interest'] = $merchant['discount_interest'];
            }else{
                if(!$conf['county_id']){
                    //如果有区域优惠利息，则按区域优惠利息计算，否则按全国规定优惠计算
                    $province_conf = M('SysInstallmentPlan')->where(['repay_times'=>$conf['repay_times'], 'county_id'=>$province_id['province_id']])->find();
                    if($province_conf){
                        $config['discount_interest'] = $province_conf['discount_interest'];
                    }
                }
            }
        }else{
            //首先判断当前产品是否为区域产品
            if($conf['county_id']){
                if($province_id['province_id'] == $conf['county_id']){
                    $config['interest_type'] = FinishModel::PROVINCE_STANDARD;
                }else{
                    BusinessException::throwException(Constant::FAILED);
                }
            }else{
                //如果有区域优惠利息，则按区域优惠利息计算，否则按全国规定优惠计算
                $province_conf = M('SysInstallmentPlan')->where(['repay_times'=>$conf['repay_times'], 'county_id'=>$province_id['province_id']])->find();
                if($province_conf){
                    $config['id'] = $province_conf['id'];
                    $config['interest_rate'] = $province_conf['interest_rate'];
                    $config['interest_type'] = FinishModel::PROVINCE_STANDARD;
                    $config['discount_interest'] = $province_conf['discount_interest'];
                }
            }
        }
        Log::write("config=".json_encode($config), Log::DEBUG);
        return $config;
    }

    public function WithdrawalsList($cash_conf, $max_cash, $init, $reviewed_amount=0, $level=0)
    {
        $amount_data = [];
        $tmp_level = 0;
        
        foreach ($cash_conf as $v){
            //按用户等级展示产品
//             if($tmp_level > $level){
//                 break;
//             }

            $detail['id'] = $v['id'];
            $detail['repay_unit'] = $v['repay_unit'];
            $detail['repay_times'] = $v['timer'];
            $conf['repay_times'] = $v['repay_times'];
            $conf['interest_rate'] = $v['interest_rate'];
            $conf['cut_interest'] = $v['cut_interest'];
            $conf['timer'] = $v['timer'];
            $cash_data = [];
            if($init){
                $unit = Constant::CASH_UNIT_INIT;
            }else{
                $unit = Constant::CASH_UNIT;
            }
            $unit=Constant::CASH_UNIT_INIT_NEW;
            for($i=0; $i<$max_cash/$unit; $i++){
                $amount = ($max_cash - $unit*($i+1))<0 ? $max_cash : $unit*($i+1);
                //如果有传金额过来，则只取这个金额相等的
                if ($reviewed_amount != 0){
                    if($reviewed_amount == $amount) {
                        $ins_data['withdrawal_amount'] = $amount;
                        $res = $this->getWithdrawalDetail($amount, $conf, $v['repay_unit']);
                        $ins_data['fee_amount'] = $res['feeAmount'];
                        $ins_data['transfer_amount'] = $res['withdrawal_amount'];
                        $ins_data['repay_total'] = $res['bill'];
                        $cash_data[] = $ins_data;
                    }
                }else{
                    $ins_data['withdrawal_amount'] = $amount;
                    $res = $this->getWithdrawalDetail($amount, $conf, $v['repay_unit']);
                    $ins_data['fee_amount'] = $res['feeAmount'];
                    $ins_data['transfer_amount'] = $res['withdrawal_amount'];
                    $ins_data['repay_total'] = $res['bill'];
                    $cash_data[] = $ins_data;
                }
            }
            
            $detail['cash_data'] = $cash_data;
            $amount_data[] = $detail;
            $tmp_level++;
            
        }
        return $amount_data;
    }

}
